package com.ericzong.util;

import java.util.Collections;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

public class ConvertUtils
{
    /**
     * 将一个整型List转换为一个形如"1-20,30-43,50,60-71"的字符串
     * @param list 指定待转换的列表
     * @return 返回字符串
     */
    public static String numbersToRangeString(List<Integer> list, String spliterator)
    {
        if (CollectionUtils.isEmpty(list))
        {
            return "";
        }
        
        if(spliterator == null || spliterator.isEmpty())
        {
            spliterator = ", ";
        }

        StringBuilder cache = new StringBuilder();
        Collections.sort(list);
        
        Integer start = null;
        Integer end = null;
        for (Integer i : list)
        {
            if(start == null)
            {
                start = i;
            }
            else
            {
                Integer lastNum = (end == null ? start : end);
                int interval = i - lastNum;
                if(interval == 1)
                {
                    end = i;
                }
                if(interval > 1)
                {
                    appendRange(cache, start, end, spliterator);
                    start = i;
                    end = null;
                }
            }
        }
        appendRange(cache, start, end, spliterator);
        
        return cache.toString();
    }
    
    private static void appendRange(StringBuilder cache, Integer start, Integer end, String spliterator)
    {
        if(cache.length() > 0)
        {
            cache.append(spliterator);
        }
        cache.append(start);
        if(end != null)
        {
            if(end - start == 1)
            {
                cache.append(spliterator);
            }
            else
            {
                cache.append('-');
            }
            cache.append(end);
        }
    }
    
}
